"""
模块名称：example_thread.py
作者：Lionel.Zhang
创建时间：2025 - 11 - 05
最后修改时间：2025 - 11 - 05
功能描述：多线程示例程序
"""

import _thread
import utime

# 全局变量用于线程控制
thread_running = True

def thread_entry_A(thread_id):
    """
    线程A的执行函数
    """
    counter = 0
    try:
        while thread_running:
            counter += 1
            current_time = utime.time()
            print('[{}] 线程 {} 运行中 - 计数：{}'.format(
                current_time, thread_id, counter))
            utime.sleep(3)
    except Exception as e:
        print('线程 {} 错误：{}'.format(thread_id, e))
    finally:
        print('线程 {} 已停止。计数：{}'.format(thread_id, counter))

def thread_entry_B(thread_id):
    """
    线程B的执行函数
    """
    counter = 0
    try:
        while thread_running:
            counter += 1
            current_time = utime.time()
            print('[{}] 线程 {} 运行中 - 计数：{}'.format(
                current_time, thread_id, counter))
            utime.sleep(3)
    except Exception as e:
        print('线程 {} 错误：{}'.format(thread_id, e))
    finally:
        print('线程 {} 已停止。计数：{}'.format(thread_id, counter))

def thread_entry_C(thread_id):
    """
    线程C的执行函数 - 新增线程
    """
    counter = 0
    try:
        while thread_running:
            counter += 1
            current_time = utime.time()
            print('[{}] 线程 {} 运行中 - 计数：{}'.format(
                current_time, thread_id, counter))
            utime.sleep(2)  # 不同的间隔时间
    except Exception as e:
        print('线程 {} 错误：{}'.format(thread_id, e))
    finally:
        print('线程 {} 已停止。计数：{}'.format(thread_id, counter))

def start_all_threads():
    """
    启动所有线程
    """
    print('正在启动所有线程，启动时间：{}'.format(utime.time()))
    
    # 启动线程A
    _thread.start_new_thread(thread_entry_A, ('A',))
    utime.sleep(0.1)
    
    # 启动线程B
    _thread.start_new_thread(thread_entry_B, ('B',))
    utime.sleep(0.1)
    
    # 启动线程C
    _thread.start_new_thread(thread_entry_C, ('C',))
    utime.sleep(0.1)
    
    print('所有线程启动成功')

def main():
    """
    主程序
    """
    global thread_running
    
    print('=== 多线程演示程序启动 ===')
    start_all_threads()
    
    # 主线程等待指定时间
    try:
        run_duration = 15  # 运行15秒
        start_time = utime.time()
        
        while utime.time() - start_time < run_duration:
            utime.sleep(1)
            elapsed = utime.time() - start_time
            remaining = run_duration - elapsed
            if remaining > 0:
                print('主线程：剩余 {:.1f} 秒'.format(remaining))
                
    except KeyboardInterrupt:
        print('用户中断程序')
    finally:
        # 停止所有线程
        print('正在停止所有线程...')
        thread_running = False
        utime.sleep(1)  # 给线程时间退出
        
    print('=== 程序结束 ===')

# 程序入口
if __name__ == '__main__':
    main()